package com.cmb.lk50.common;

import com.cmb.lk50.common.extractor.BodyParamExtractor;
import com.cmb.lk50.common.receiver.ResponseBodyReceiver;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Author       : 蒋俊钊 80256973
 * Date         : 2019/11/15
 * Copyright    (C) ChinaMerchantsBank
 */
@WebFilter(urlPatterns = {"/*"})
public class ServletWrapperFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {
    }

    /**
     *  将request和response的body wrapper
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if(request instanceof HttpServletRequest) {
            BodyParamExtractor bodyParamExtractor = new BodyParamExtractor();
            request = bodyParamExtractor.new RequestBodyExtractorWrapper((HttpServletRequest) request);
        }

        if(response instanceof HttpServletResponse) {
            ResponseBodyReceiver responseBodyReceiver = new ResponseBodyReceiver();
            response = responseBodyReceiver.new ResponseBodyReceiverWrapper((HttpServletResponse) response);
        }

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }

}
